<template>
  <div class="community-post-container">
    <a-card class="post-card">
      <div class="card-header">
        <div class="header-left">
          <a-button type="link" @click="goBack">
            <left-outlined />
            发布文章
          </a-button>
        </div>
        <div class="header-right">
          <a-button type="text" @click="switchEditor">
            <swap-outlined />
            {{ isMarkdown ? '切换富文本编辑器' : '切换MD编辑器' }}
          </a-button>
          <a-button type="primary" @click="showPublishDrawer" :loading="submitting">
            发布文章
          </a-button>
        </div>
      </div>

      <div class="post-form">
        <!-- 标题输入 -->
        <div class="title-wrapper">
          <a-input
            v-model:value="postForm.title"
            placeholder="请输入文章标题..."
            class="title-input"
            :maxLength="100"
            show-count
          />
        </div>

        <!-- 内容编辑器 -->
        <div v-if="!isMarkdown" class="editor-container">
          <QuillEditor
            v-model:content="postForm.content"
            contentType="html"
            theme="snow"
            toolbar="full"
            class="content-editor"
          />
        </div>
        <div v-else class="editor-container">
          <MdEditor v-model="postForm.content" />
        </div>

        <!-- 文章摘要 -->
        <a-form-item label="文章摘要" class="summary-input">
          <a-textarea
            v-model:value="postForm.summary"
            placeholder="请输入文章摘要..."
            :rows="3"
            :maxLength="200"
            show-count
          />
        </a-form-item>
      </div>
    </a-card>

    <!-- 发布设置抽屉 -->
    <a-drawer
      title="准备好发布文章了？"
      :width="420"
      placement="right"
      :visible="drawerVisible"
      @close="drawerVisible = false"
      class="publish-drawer"
    >
      <div class="drawer-content">
        <p class="drawer-tip">
          在发布文章前，请检查文章的设置并阅读
          <a href="#" class="link">《社区内容公约》</a>
        </p>

        <div class="drawer-section">
          <h3 class="section-title">文章统计信息</h3>
          <div class="count-item">
            <span class="count-label">字数统计:</span>
            <span class="count-value"
              >{{ postForm.content ? postForm.content.length : 0 }}个字符</span
            >
          </div>
        </div>

        <div class="drawer-section">
          <h3 class="section-title">投稿到社区</h3>
          <a-select
            v-model:value="postForm.communityId"
            placeholder="请选择投稿社区"
            :options="communityOptions"
            class="full-width"
          />
          <div class="hint-text">请选择一个社区，如果列表为空，请先加入社区</div>
        </div>

        <div class="drawer-section">
          <h3 class="section-title">标签设置</h3>
          <a-select
            v-model:value="postForm.tags"
            mode="tags"
            placeholder="请输入文章标签"
            :maxTagCount="5"
            :options="tagOptions"
            class="full-width"
          />
          <div class="hint-text">最多可添加5个标签，合适的标签有助于文章被更多人看到</div>
        </div>

        <div class="drawer-section">
          <h3 class="section-title">上传附件</h3>
          <a-upload
            v-model:file-list="imageFileList"
            list-type="picture"
            :max-count="1"
            :before-upload="beforeImageUpload"
            :custom-request="handleImageChange"
          >
            <a-button>
              <upload-outlined />
              点击上传
            </a-button>
            <template #itemRender="{ file }">
              <div class="upload-item">
                <img :src="file.url || file.thumbUrl" class="upload-preview" />
                <a-button type="text" danger @click="removeImage">
                  <delete-outlined />
                </a-button>
              </div>
            </template>
          </a-upload>
          <div class="hint-text">支持jpg, bmp, png, gif等格式，大小不超过500MB</div>
        </div>

        <div class="drawer-section">
          <h3 class="section-title">同步到以下平台</h3>
          <div class="platform-sync">
            <a-checkbox v-model:checked="syncPlatforms.zhihu">知乎</a-checkbox>
            <a-checkbox v-model:checked="syncPlatforms.csdn">CSDN</a-checkbox>
            <a-checkbox v-model:checked="syncPlatforms.juejin">掘金</a-checkbox>
          </div>
        </div>

        <div class="drawer-footer">
          <a-button @click="drawerVisible = false" style="margin-right: 12px">取消</a-button>
          <a-button type="primary" @click="submitPost" :loading="submitting">发布文章</a-button>
        </div>
      </div>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { LeftOutlined, SwapOutlined, UploadOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import { message, type UploadProps } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import {
  addCommunityPostUsingPost,
  uploadPostPictureUsingPost,
} from '@/api/communityPostController'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import MdEditor from '@/components/MdEditor.vue'

const router = useRouter()
const submitting = ref(false)
const imageFileList = ref<any[]>([])
const drawerVisible = ref(false)
const isMarkdown = ref(false)

// 表单状态
const postForm = reactive<API.CommunityPostAddRequest>({})

// 同步平台设置
const syncPlatforms = reactive({
  zhihu: false,
  csdn: false,
  juejin: false,
})

// 社区选项
const communityOptions = ref([
  { value: null, label: '全站' },
  { value: 1, label: '前端技术' },
  { value: 2, label: '后端开发' },
  { value: 3, label: 'AI与大数据' },
  { value: 4, label: '移动开发' },
])

// 标签选项
const tagOptions = ref([
  { value: '风景', label: '风景' },
  { value: '动漫', label: '动漫' },
  { value: 'Wallpaper', label: 'Wallpaper' },
  { value: '人文', label: '人文' },
  { value: 'AI绘画', label: 'AI绘画' },
  { value: '艺术', label: '艺术' },
  { value: '配色', label: '配色' },
])

// 返回上一页
const goBack = () => {
  router.back()
}

// 切换编辑器
const switchEditor = () => {
  isMarkdown.value = !isMarkdown.value
}

// 显示发布抽屉
const showPublishDrawer = () => {
  drawerVisible.value = true
}

// 图片上传前检查
const beforeImageUpload = (file: UploadProps['fileList'][number]) => {
  // 校验图片格式
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('不支持上传该格式的图片，推荐 jpg 或 png')
  }
  // 校验图片大小
  const isLt2M = file.size / 1024 / 1024 < 6
  if (!isLt2M) {
    message.error('不能上传超过 6M 的图片')
  }
  return isJpgOrPng && isLt2M
}

// 处理图片变更
const handleImageChange = async ({ file }: any) => {
  const response = await uploadPostPictureUsingPost({}, file)
  if (response.data.code === 0) {
    postForm.imageUrl = response.data.data
    message.success(`${file.name} 上传成功`)
  } else {
    message.error(`${file.name} 上传失败`)
  }
}

// 移除图片
const removeImage = () => {
  imageFileList.value = []
  postForm.imageUrl = ''
}

// 提交表单
const submitPost = async () => {
  // 表单验证
  if (!postForm.title) {
    message.error('标题不能为空')
    return
  }
  if (!postForm.content) {
    message.error('内容不能为空')
    return
  }

  submitting.value = true
  try {
    const response = await addCommunityPostUsingPost(postForm, {})

    if (response.data.code === 0) {
      message.success('文章发布成功')
      router.push(`/community/postDetail/${response.data.data}`)
    } else {
      message.error(`发布失败: ${response.data.message}`)
    }
  } catch (error) {
    console.error('发布文章出错:', error)
    message.error('发布失败，请稍后重试')
  } finally {
    submitting.value = false
    drawerVisible.value = false
  }
}

const loginUserStore = useLoginUserStore();

// 加载社区和标签选项
onMounted(async () => {
  try {
    if (!loginUserStore.loginUser.id) {
      router.replace({
        path: '/user/login',
        query: { redirect: '/community/createPost' },
      })
    }
    // 这里可以添加加载社区和标签列表的API调用
    // const communitiesResponse = await axios.get('/api/community/list');
    // const tagsResponse = await axios.get('/api/tags/list');
    // communityOptions.value = communitiesResponse.data.data?.map(item => ({ value: item.id, label: item.name })) || [];
    // tagOptions.value = tagsResponse.data.data?.map(item => ({ value: item.name, label: item.name })) || [];
  } catch (error) {
    console.error('加载数据出错:', error)
    message.error('加载社区和标签数据失败')
  }
})
</script>

<style scoped>
.community-post-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  box-sizing: border-box;
}

.post-card {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  width: 100%;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 10px;
}

.header-left {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
}

.header-right {
  display: flex;
  gap: 10px;
}

.post-form {
  display: flex;
  flex-direction: column;
  width: 100%;
  padding: 0 20px 20px;
  box-sizing: border-box;
}

.title-wrapper {
  margin-bottom: 24px;
  position: relative;
}

.title-input {
  font-size: 28px;
  font-weight: 500;
  border: none;
  border-bottom: 1px solid #f0f0f0;
  padding: 16px 0;
  width: 100%;
  transition: all 0.3s ease;
}

.title-input:focus {
  border-color: #1890ff;
  box-shadow: none;
}

.title-input::placeholder {
  color: #bbb;
  font-weight: 400;
}

.editor-container {
  width: 100%;
  margin-bottom: 30px;
  border-radius: 4px;
  overflow: hidden;
}

:deep(.ql-toolbar) {
  border-radius: 4px 4px 0 0;
  background-color: #fafafa;
  border: 1px solid #f0f0f0;
}

:deep(.ql-container) {
  border-radius: 0 0 4px 4px;
  font-size: 16px;
  line-height: 1.6;
  border: 1px solid #f0f0f0;
  border-top: none;
  height: 500px !important; /* 增加编辑器高度 */
}

.content-editor {
  width: 100%;
  box-sizing: border-box;
}

.summary-input {
  width: 100%;
  margin-top: 10px;
}

.summary-input :deep(.ant-form-item-label) {
  font-weight: 500;
  margin-bottom: 8px;
}

.summary-input :deep(.ant-form-item-control-input) {
  width: 100%;
}

.summary-input :deep(.ant-input) {
  width: 100%;
  box-sizing: border-box;
  border-radius: 4px;
  border: 1px solid #f0f0f0;
  transition: all 0.3s ease;
}

.summary-input :deep(.ant-input:focus) {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
}

/* Drawer styling */
.publish-drawer :deep(.ant-drawer-content-wrapper) {
  box-shadow: -10px 0 20px rgba(0, 0, 0, 0.1);
  max-width: 100%;
}

.publish-drawer :deep(.ant-drawer-header) {
  border-bottom: 1px solid #f5f5f5;
  padding: 20px 24px;
}

.publish-drawer :deep(.ant-drawer-title) {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.publish-drawer :deep(.ant-drawer-body) {
  padding: 0;
  display: flex;
  flex-direction: column;
  height: calc(100% - 55px);
}

.drawer-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.drawer-tip {
  background-color: #f9f9f9;
  padding: 12px 16px;
  border-radius: 6px;
  margin-bottom: 24px;
  font-size: 14px;
  color: #666;
}

.link {
  color: #1890ff;
  text-decoration: none;
}

.drawer-section {
  margin-bottom: 24px;
  padding-bottom: 24px;
  border-bottom: 1px solid #f0f0f0;
}

.drawer-section:last-child {
  border-bottom: none;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  color: #333;
}

.count-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.count-label {
  color: #666;
}

.count-value {
  font-weight: 500;
}

.full-width {
  width: 100%;
}

.hint-text {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

.platform-sync {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.drawer-footer {
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
  text-align: right;
  background: #fff;
}

.upload-item {
  display: flex;
  align-items: center;
  margin: 10px 0;
}

.upload-preview {
  width: 100px;
  height: 100px;
  object-fit: cover;
  margin-right: 10px;
  border-radius: 4px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .community-post-container {
    padding: 10px;
  }

  .platform-sync {
    flex-direction: column;
    gap: 8px;
  }

  .publish-drawer :deep(.ant-drawer-content-wrapper) {
    width: 100% !important;
  }
}
</style>
